﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace BibleService.Lib
{
	/// <summary>
	/// 书本管理
	/// </summary>
	public class Book
	{
		public int BookID{get;set;}
		public String Name{get;set;}
		public String EnName{get;set;}
		public String[] Tag{get;set;}
		public String PartCode{get;set;}
		public int ChapterCount{get;set;}

		/// <summary>
		/// 添加书本
		/// </summary>
		public Book Add()
		{	
			string tagString=string.Empty;
			if(this.Tag!=null)
				tagString=string.Join(",",this.Tag);
				
			string insertBookSql = string.Format("Insert Into Books(Name,EnName,Tag,PartCode,ChapterCount) values('{0}','{1}','{2}','{3}','{4}')",
					this.Name,
					this.EnName,
					tagString,
					this.PartCode,
					this.ChapterCount);
			Lib._SqlHelper.Execute<Int32>(insertBookSql);
			this.BookID = (Int32)Lib._SqlHelper.GetSingCell<Int64>("select max(bookid) from Books");
			return this;
		}
		
		private static List<Book> _getList(string sqlString)
		{
			List<Book> list = new List<Book>();
			using (var dataReader = _SqlHelper.GetList(sqlString))
			{
				while(dataReader.Read())
				{
					var model = new Book();
					model.BookID =dataReader.GetInt32(0);
					model.Name = dataReader.GetString(1);
					model.EnName = dataReader.GetString(2);
					model.PartCode = dataReader.GetString(3);
					string tags = dataReader.GetString(4);
					if (string.IsNullOrEmpty(tags) == false)
						model.Tag = tags.Split(',');
					model.ChapterCount = dataReader.GetInt32(5);

					list.Add(model);
				}
			}
			return list;
		}
		/// <summary>
		/// 获取所有列表
		/// </summary>
		/// <returns></returns>
		public static List<Book> GetAllBookList()
		{
			string selectSql = "select BookID,Name,EnName,PartCode,Tag,ChapterCount from Books";
			return _getList(selectSql);
		}
		
		/// <summary>
		/// 获取旧约目录列表
		/// </summary>
		/// <returns></returns>
		public static List<Book> GetOldTestamentList()
		{
			string selectSql = "select BookID,Name,EnName,PartCode,Tag,ChapterCount from Books where PartCode='OldTestament'";
			return _getList(selectSql);
		}
		/// <summary>
		/// 获取新约目录列表
		/// </summary>
		/// <returns></returns>
		public static List<Book> GetNewTestamentList()
		{
			string selectSql = "select BookID,Name,EnName,PartCode,Tag,ChapterCount from Books where PartCode='NewTestament'";
			return _getList(selectSql);
		}		
		/// <summary>
		/// 根据标签获取列表
		/// </summary>
		/// <param name="tagName"></param>
		/// <returns></returns>
		public static List<Book> GetListByTag(string tagName)
		{
			string selectSql = string.Format("select BookID,Name,EnName,PartCode,Tag,ChapterCount from Books where Tag like '%{0}%'", tagName);
			return _getList(selectSql);
		}		
	}
}
